package com.ruoyi.college.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.college.domain.Class;
import com.ruoyi.college.service.IClassService;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.college.mapper.StudentMapper;
import com.ruoyi.college.domain.Student;
import com.ruoyi.college.service.IStudentService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import javax.validation.Validator;

/**
 * 学生信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-25
 */
@Service
public class StudentServiceImpl implements IStudentService 
{
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private IClassService classService;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询学生信息
     * 
     * @param studentId 学生信息主键
     * @return 学生信息
     */
    @Override
    public Student selectStudentByStudentId(Long studentId)
    {
        return studentMapper.selectStudentByStudentId(studentId);
    }

    /**
     * 查询学生信息列表
     * 
     * @param student 学生信息
     * @return 学生信息
     */
    @Override
    public List<Student> selectStudentList(Student student)
    {
        List<Student> students = studentMapper.selectStudentList(student);
        students.forEach(item->{
            Class aClass = classService.selectClassByClassId(item.getClassId());
            item.setClassName(aClass.getClassName());
        });
        return students;
    }

    /**
     * 新增学生信息
     * 
     * @param student 学生信息
     * @return 结果
     */
    @Override
    public int insertStudent(Student student)
    {
        student.setCreateTime(DateUtils.getNowDate());
        int count = studentMapper.insertStudent(student);
        SysRole role = roleMapper.selectRoleByRoleKey("studentSide");
        List<Class> classList = classService.selectClassList(new Class());
        Map<String, Long> classMap = classList.stream().collect(Collectors.toMap(Class::getClassName, Class::getClassId));
        student.setClassId(classMap.get(student.getClassName()));
        SysUser user = new SysUser();
        user.setCreateBy(ShiroUtils.getLoginName());
        user.setLoginName(student.getStudentNo());
        user.setUserName(student.getName());
        String password = configService.selectConfigByKey("sys.user.initPassword");
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex());
        user.setSex(student.getGender());
        user.setRoleIds(new Long[]{role.getRoleId()});
        userService.insertUser(user);
        return count;
    }

    /**
     * 修改学生信息
     * 
     * @param student 学生信息
     * @return 结果
     */
    @Override
    public int updateStudent(Student student)
    {
        student.setUpdateTime(DateUtils.getNowDate());
        return studentMapper.updateStudent(student);
    }

    /**
     * 批量删除学生信息
     * 
     * @param studentIds 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentByStudentIds(String studentIds)
    {
        return studentMapper.deleteStudentByStudentIds(Convert.toStrArray(studentIds));
    }

    /**
     * 删除学生信息信息
     * 
     * @param studentId 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentByStudentId(Long studentId)
    {
        return studentMapper.deleteStudentByStudentId(studentId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertBatchStudent(List<Student> studentList, boolean updateSupport, String operName) {
        if (studentList == null || studentList.isEmpty()) {
            throw new ServiceException("导入学生数据不能为空！");
        }
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        int successNum = 0;
        int failureNum = 0;
        //校验传入的学生信息是否重复
        this.validateStudentListRepeat(studentList);

        List<Class> classList = classService.selectClassList(new Class());
        Map<String, Long> classMap = classList.stream().collect(Collectors.toMap(Class::getClassName, Class::getClassId));
        List<Student> students = studentMapper.selectStudentList(new Student());
        Map<String, Student> studentMap = students.stream()
                .collect(Collectors.toMap(Student::getStudentNo, student -> student));
        List<SysUser> userList = userService.selectUserList(new SysUser());
        Map<String, SysUser> userMap = userList.stream()
                .collect(Collectors.toMap(SysUser::getLoginName, sysUser -> sysUser));
        SysRole role = roleMapper.selectRoleByRoleKey("studentSide");
        List<Student> studentUpdate = new ArrayList<>();
        List<Student> studentInsert = new ArrayList<>();
        List<SysUser> userUpdate = new ArrayList<>();
        List<SysUser> userInsert = new ArrayList<>();
        for (Student student : studentList) {
            // 验证是否存在这个用户
            Student studentOld = studentMap.get(student.getStudentNo());
            if (studentOld == null) {
                student.setClassId(classMap.get(student.getClassName()));
                studentInsert.add(student);
                SysUser user = new SysUser();
                user.setCreateBy(operName);
                user.setLoginName(student.getStudentNo());
                user.setUserName(student.getName());
                String password = configService.selectConfigByKey("sys.user.initPassword");
                user.setSalt(ShiroUtils.randomSalt());
                user.setPassword(new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex());
                user.setSex(student.getGender());
                user.setRoleIds(new Long[]{role.getRoleId()});
                userInsert.add(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、学生姓名 ").append(student.getName()).append(" 导入成功");
            } else if (updateSupport) {
                student.setStudentId(studentOld.getStudentId());
                studentUpdate.add(student);
                SysUser user = userMap.get(student.getStudentNo());
                user.setUpdateTime(new Date());
                user.setUpdateBy(operName);
                user.setUserName(student.getName());
                user.setSex(student.getGender());
                userUpdate.add(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、学生姓名 ").append(student.getName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、学生姓名 ").append(student.getName()).append(" 已存在");
            }
        }
        this.handleTeacherUserBatch(studentUpdate, studentInsert, userUpdate, userInsert);
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    private void validateStudentListRepeat(List<Student> studentList) {
        Set<String> studentSet = new HashSet<>();
        for (Student student : studentList) {
            if (!studentSet.contains(student.getStudentNo())) {
                studentSet.add(student.getStudentNo());
            } else {
                throw new ServiceException("导入学生数据不能有重复学号！");
            }
        }
    }

    private void handleTeacherUserBatch(List<Student> studentsUpdate, List<Student> studentsInsert, List<SysUser> userUpdate,
                                        List<SysUser> userInsert) {
        if (!studentsInsert.isEmpty()) {
            studentsInsert.forEach(teacher -> {
                studentMapper.insertStudent(teacher);
            });
        }
        if (!studentsUpdate.isEmpty()) {
            studentsUpdate.forEach(teacher -> {
                studentMapper.updateStudent(teacher);
            });
        }
        if (!userInsert.isEmpty()) {
            userInsert.forEach(user -> {
                userService.insertUser(user);
            });
        }
        if (!userUpdate.isEmpty()) {
            userUpdate.forEach(user -> {
                userService.updateUser(user);
            });
        }
    }
}
